<template>
  <a-modal
    :visible="visible"
    :title="title"
    :confirmLoading="confirmLoading"
    @cancel="close"
    @ok="handleOk"
    :destroyOnClose="true"
  >
    <a-form-model
      ref="rulesForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-model-item label="业务类型">
        <a-radio-group v-model="form.opeType">
          <a-radio :value="1">装货</a-radio>
          <a-radio :value="2">卸货</a-radio>
          <a-radio :value="3">提箱</a-radio>
          <a-radio :value="4">空车</a-radio>
        </a-radio-group>
      </a-form-model-item>

      <template v-if="!form.isJiahuaOriPort">
        <a-form-model-item label="地址类型">
          <a-radio-group v-model="form.addressType" @change="changeAddr">
            <a-radio :value="1">港口</a-radio>
            <a-radio :value="2">门点</a-radio>
          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item v-if="form.addressType===2" label="地址" prop="address">
          <a-cascader
            :value="pcaStr"
            :options="options"
            :fieldNames="{label: 'area', value: 'area', children: 'childList'}"
            placeholder="省/市/区县"
            @change="onChange"
          />
          <a-input
            v-model="form.address"
            :max-length="100"
            placeholder="详细地址"
            @change="() => this.$refs.rulesForm.validateField('address')"
          />
        </a-form-model-item>

        <a-form-model-item v-if="form.addressType===1" label="港口" prop="portId">
          <a-select
            show-search
            v-model="form.portId"
            :show-arrow="false"
            :filter-option="false"
            :default-active-first-option="false"
            :not-found-content="null"
            @search="value => handlePortNameChange(value)"
            @select="emptyChange"
          >
            <a-select-option v-for="d in portList" :key="d.id">{{ d.name }}</a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="联系人" prop="linkMan">
          <a-input v-model="form.linkMan" :max-length="10" />
        </a-form-model-item>
        <a-form-model-item label="手机号码" prop="linkManPhone">
          <a-input v-model="form.linkManPhone" :max-length="11" />
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-textarea :rows="4" v-model="form.remark" />
        </a-form-model-item>
      </template>
    </a-form-model>
  </a-modal>
</template>

<script>
import { queryBaseAreaList, queryPortNameList } from '@/api'
import { addOrderTruckAddress } from '@/api/landCenter'
import debounce from 'lodash/debounce'
const defaultForm = () => ({
  key: -1,
  opeType: 1, // 1装货，2卸货，3提箱 4空车
  addressType: 1, // 1港口，2门点
  portId: '', // 港口id
  portName: '',
  province: '', // 省
  city: '', // 市
  area: '', // 区
  address: '', // 详细地址
  linkMan: '', // 联系人
  linkManPhone: '', // 联系人手机号
  remark: '', // 备注
  isJiahuaOriPort: false
})
const fomrMessage = `必填项不能为空`

export default {
  name: 'loadingOrNot',
  props: {
    visible: Boolean,
    data: Object
  },
  data () {
    this.handlePortNameChange = debounce(this.handlePortNameChange, 800)

    const addressValidator = (rule, value, callback) => {
      if (!this.form.area || !this.form.address) {
        callback(new Error(fomrMessage))
      } else {
        callback()
      }
    }

    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      options: [],
      portList: [],
      form: defaultForm(),
      confirmLoading: false,
      rules: {
        portId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        address: [{ required: true, validator: addressValidator, trigger: ['blur', 'change'] }],
        linkMan: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        linkManPhone: [{ required: true, message: fomrMessage, trigger: 'blur' }, { message: '手机号码限制纯11位数字', pattern: /^\d+$/, trigger: 'blur' }]
      }
    }
  },
  computed: {
    title () {
      return this.data ? '编辑装卸门点' : '添加装卸门点'
    },
    pcaStr () {
      return this.form.area ? [this.form.province, this.form.city, this.form.area] : null
    }
  },
  methods: {
    changeAddr () {
      if (this.form.addressType === 1) {
        this.form.portId = ''
        this.emptyChange()
      } else if (this.form.addressType === 2) {
        this.form.province = ''
        this.form.city = ''
        this.form.area = ''
        this.form.address = ''
      }
    },
    queryAddress () {
      queryBaseAreaList({})
        .then(res => {
          this.options = res.data
        })
        .catch(rs => { })
    },
    onChange (value, selectedOptions) {
      this.form.province = value[0]
      this.form.city = value[1]
      this.form.area = value[2]
    },
    handlePortNameChange (nameLike = '') {
      queryPortNameList({
        nameLike,
        status: 1
      }).then(res => {
        this.portList = res.data
      })
    },
    emptyChange () {
      this.handlePortNameChange()
    },
    close () {
      this.$emit('closeIt', false)
    },
    handleOk () {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          if (!this.form.isJiahuaOriPort && this.form.addressType === 1) {
            const t = this.portList.filter(v => v.id === this.form.portId)[0]
            if (t) this.form.portName = t.name
          }
          addOrderTruckAddress(this.form).then(rsp => {
            this.$message.success('保存成功')
            this.$emit('closeIt', true)
            this.confirmLoading = false
          }).catch(() => { this.confirmLoading = false })
        }
      })
    }
  },
  mounted () {
    this.queryAddress()
  },
  watch: {
    visible () {
      if (this.visible) {
        this.handlePortNameChange()
        if (this.data.orderTruckId) { // 新增
          Object.assign(this.form, defaultForm(), this.data)
          this.handlePortNameChange(this.data.portName)
        } else {
          Object.assign(this.form, this.data)
        }
      }
    }
  }
}
</script>
